package com.bdqn.springbootwebsocket.websocket;

import com.alibaba.fastjson.JSON;
import com.bdqn.springbootwebsocket.pojo.Message;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

//value 代表 与前端的连接  通道  前缀
@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfigure.class)
@Component
public class SeverPoint {
    //用来保存所有在线人的endpointConfig对象
    public static Map<String, SeverPoint> onlineUser = new ConcurrentHashMap<>();
    //session 用来发送wensocket消息的
    public Session session;
    //endpointConfig每当有用户在前端登录成功后用户的webssocket对象

    //会话 HttpSession 当前登录人的用户信息，在HttpSession里面
    public HttpSession httpSession;

    //用户建立连接触发的
    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        this.session = session;
        //将endpointConfig对象存入oblineUser在线用户集合
        this.httpSession = (HttpSession) endpointConfig.getUserProperties().get(HttpSession.class.getName());
        String username = (String) httpSession.getAttribute("user");
        onlineUser.put(username, this);
        Message message = new Message();
        message.setSystem(true);
        message.setToWhere(onlineUser.keySet());
        message.setContent(username);
        //发送消息
        this.sendMessage(message);
    }

    public void sendMessage(Message message) {
        try {
            Set<String> names = message.getToWhere();
            if (names != null) {
                for (String name : names) {
                    SeverPoint severPoint = onlineUser.get(name);
                    severPoint.session.getBasicRemote().sendText(JSON.toJSONString(message));
                }
            } else {
                SeverPoint severPoint = onlineUser.get(message.getToUser());
                severPoint.session.getBasicRemote().sendText(JSON.toJSONString(message));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("有消息进来要发送！");
        System.out.println(message);
        Message message1 = JSON.parseObject(message, Message.class);
        sendMessage(message1);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {

    }
}
